package org.springblade.common.aspect;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IUserService;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description 飞书接口切面
 * @Author ysq
 * @Date 2024/05/22
 **/
@Aspect
@Component
@Slf4j
public class FeishuTableInterfaceAspect {

	@Resource
	private BladeRedis bladeRedis;
	@Resource
	private Environment environment;
	@Resource
	private IUserService userService;
	private static final String FEISHU_VALUE = "feishu:token";

	@Pointcut("@annotation(org.springblade.common.annotation.FeishuTableInterface)")
    public void feiShuInterface() {
    }

	/**
	 * 前置通知
	 * @param joinPoint
	 */
	@Before("feiShuInterface()")
	public void before(JoinPoint joinPoint) {
		throw new ServiceException("飞书配件流程已禁用，请前往梯无忧操作!");
		// 获取方法参数
//		Object[] args = joinPoint.getArgs();
//		Map<String, Object> methodParamMap = (Map<String, Object>) args[0];
//		if (!methodParamMap.containsKey("appToken") || !methodParamMap.containsKey("tableId")) {
//			throw new ServiceException("非法请求");
//		}
//
//		//当前环境
//		String curEnvironment = environment.getActiveProfiles()[0];
//		String appToken = methodParamMap.get("appToken").toString();
//		String tableId = methodParamMap.get("tableId").toString();
//		FeiShuDocumentEnum fsEnum = FeiShuDocumentEnum.getEnum(curEnvironment, appToken, tableId);
//		if (fsEnum == null) {
//            throw new ServiceException("未找到相关多维表格配置");
//        }
//
//		UserInfo userInfo = userService.userInfo(fsEnum.getTenantId(), "feishu", DigestUtil.hex(DigestUtil.md5Hex("123456")), UserEnum.OTHER);
//		if (userInfo == null) {
//			throw new ServiceException("未配置飞书账号");
//		}
//
//		String tokenKey = FEISHU_VALUE.concat(StringPool.DASH).concat(fsEnum.getTenantId());
//		String accessToken = bladeRedis.get(tokenKey);
//		if (Func.isBlank(accessToken)) {
//			accessToken = getAccessToken(userInfo, tokenKey);
//		}
//
//		Claims claims = AuthUtil.parseJWT(accessToken);
//		if (claims == null) {
//			accessToken = getAccessToken(userInfo, tokenKey);
//			claims = AuthUtil.parseJWT(accessToken);
//        }
//
//		String clientId = Func.toStr(claims.get(TokenConstant.CLIENT_ID));
//		Long userId = Func.toLong(claims.get(TokenConstant.USER_ID));
//		String tenantId = Func.toStr(claims.get(TokenConstant.TENANT_ID));
//		String oauthId = Func.toStr(claims.get(TokenConstant.OAUTH_ID));
//		String deptId = Func.toStrWithEmpty(claims.get(TokenConstant.DEPT_ID), StringPool.MINUS_ONE);
//		String postId = Func.toStrWithEmpty(claims.get(TokenConstant.POST_ID), StringPool.MINUS_ONE);
//		String roleId = Func.toStrWithEmpty(claims.get(TokenConstant.ROLE_ID), StringPool.MINUS_ONE);
//		String account = Func.toStr(claims.get(TokenConstant.ACCOUNT));
//		String roleName = Func.toStr(claims.get(TokenConstant.ROLE_NAME));
//		String userName = Func.toStr(claims.get(TokenConstant.USER_NAME));
//		String nickName = Func.toStr(claims.get(TokenConstant.NICK_NAME));
//		Kv detail = Kv.create().setAll((Map<? extends String, ?>) claims.get(TokenConstant.DETAIL));
//		BladeUser bladeUser = new BladeUser();
//		bladeUser.setClientId(clientId);
//		bladeUser.setUserId(userId);
//		bladeUser.setTenantId(tenantId);
//		bladeUser.setOauthId(oauthId);
//		bladeUser.setAccount(account);
//		bladeUser.setDeptId(deptId);
//		bladeUser.setPostId(postId);
//		bladeUser.setRoleId(roleId);
//		bladeUser.setRoleName(roleName);
//		bladeUser.setUserName(userName);
//		bladeUser.setNickName(nickName);
//		bladeUser.setDetail(detail);
//		HttpServletRequest request = WebUtil.getRequest();
//		// 设置到 request 中
//		request.setAttribute("_BLADE_USER_REQUEST_ATTR_", bladeUser);
	}

	/**
	 * 生成token
	 * @param userInfo
	 * @param tokenKey
	 * @return
	 */
	private String getAccessToken(UserInfo userInfo, String tokenKey) {
		Kv kv = TokenUtil.createAuthInfo(userInfo);
		String accessToken = kv.getStr(TokenConstant.ACCESS_TOKEN);
		long expiresIn = kv.getLong(TokenConstant.EXPIRES_IN);
		bladeRedis.setEx(tokenKey, accessToken, expiresIn);
		return accessToken;
	}

}
